package com.wawei.seeds;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;

import com.wawei.seeds.adapter.WalnutMainActivityAdapter;
import com.wawei.seeds.champion.ChampionActivity;
import com.wawei.seeds.me.MeMainActivity;
import com.wawei.seeds.model.ExpertInfo;
import com.wawei.seeds.model.HeroInfo;
import com.wawei.seeds.model.WalnutMainEvent;
import com.wawei.seeds.services.WalnutExpertServiceHandler;
import com.wawei.seeds.services.WalnutMainServiceHandler;
import com.wawei.seeds.services.WalnutRegAuthServiceHandler;
import com.wawei.seeds.utils.ImageAndAnimateUtils;
import com.wawei.seeds.utils.ImageLoader;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.PullupToMoreListView;
import com.wawei.seeds.utils.RetrofitNetworkService;
import com.wawei.seeds.utils.WalnutBaseNofityHandler;
import com.wawei.seeds.utils.WalnutNotifyHandler;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.RestAdapter;

/**
 *
 * Created by t27891 on 15/6/20.
 */
public class WalnutMainActivity extends ActionBarActivity {
    @InjectView(R.id.walnut_logo)ImageView logoView;
    @InjectView(R.id.walnut_home_pull_refresh)SwipeRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.walnut_event_list)PullupToMoreListView eventList;
    @InjectView(R.id.main_progress)View progress;

    private WalnutMainActivityAdapter activityAdapter;
    private WalnutEventHandler handler;
    private WalnutMainServiceHandler serviceHandler;

    public static final String EXIT = "EXIT";
    public static final int USER_LOGIN = 1;
    public static final int CHECK_EXPERT = 2;

    private int pageNumber = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_walnut_main);
        ButterKnife.inject(this);

        progress.setVisibility(View.VISIBLE);

        serviceHandler = new WalnutMainServiceHandler(this);
        handler = new WalnutEventHandler(this);

        //initHeroDataset is async
        initHeroDataset();
        init();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if(intent.getBooleanExtra(EXIT,false)){
            finish();
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        SeedsApp app = (SeedsApp)getApplication();
        HeroInfo loginUser = (HeroInfo)app.getSession().get(SeedsApp.LOGIN_USER);
        ImageLoader imageLoader = new ImageLoader(this);
        if(null != loginUser) {
            ImageAndAnimateUtils.showPersonHeaderPortait(imageLoader, logoView, loginUser.headPortrait);
        }
        else {// non-login, so login background automatically
            imageLoader.loadImageByResources(R.drawable.walnut_logo, logoView, true, false);

            RestAdapter adapter = RetrofitNetworkService.makeAsyncRestAdapter();
            WalnutRegAuthServiceHandler regAuthServiceHandler = new WalnutRegAuthServiceHandler();

            HeroInfo heroInfo = new HeroInfo();
            heroInfo.userName = PrefUtils.getPrefUser(this);
            heroInfo.password = PrefUtils.getPrefPassword(this);

            Bundle bundle = new Bundle();
            bundle.putSerializable(SeedsApp.LOGIN_USER, heroInfo);

            regAuthServiceHandler.login(adapter, bundle, handler, USER_LOGIN);
        }
    }

    private void initHeroDataset(){
        RestAdapter adapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.retrieveHeroEvents(adapter, 0, handler, WalnutNotifyHandler.INIT_ACHIEVE_DATA);
    }

    private void init(){
        swipeRefreshLayout.setColorSchemeResources(R.color.swipe_color_1
                , R.color.swipe_color_2
                , R.color.swipe_color_3
                , R.color.swipe_color_4);

        /* When user do the swipe to refresh gesture, SwipeRefreshLayout invokes the onRefresh method
           to refresh the content.
         */
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!swipeRefreshLayout.isRefreshing()) {
                    swipeRefreshLayout.setRefreshing(true);
                }
                refreshNewEvents();
            }
        });

        eventList.setOnLoadMoreListener(new PullupToMoreListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                refreshOldEvents();
            }
        });

        eventList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectedEventItem(parent, view, position, id);
            }
        });

        logoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WalnutMainActivity.this, MeMainActivity.class);
                WalnutMainActivity.this.startActivity(intent);
            }
        });
    }

    /**
     * Event item is selected by user
     * @param parent    a adapter view
     * @param view      the view caused the call
     * @param position  the position of the event item in event list
     * @param id        the id (non-use)
     */
    private void selectedEventItem(AdapterView<?> parent, View view, int position, long id){
        WalnutMainEvent item = (WalnutMainEvent)parent.getAdapter().getItem(position);

        Intent itemSelectedIntent = new Intent(this, ChampionActivity.class);
        itemSelectedIntent.putExtra(ChampionActivity.ITEM_DATA, item);
        startActivity(itemSelectedIntent);
    }

    /**
     * Response to user's refresh action to refresh the content
     */
    private void refreshNewEvents(){
        RestAdapter adapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.retrieveHeroEvents(adapter, 0, handler, WalnutNotifyHandler.LOAD_NEW_ACHIEVE_DATA);
    }

    /**
     * Reload the content
     */
    private void refreshOldEvents(){
        RestAdapter adapter = RetrofitNetworkService.makeAsyncRestAdapter();
        serviceHandler.retrieveHeroEvents(adapter, pageNumber, handler, WalnutNotifyHandler.LOAD_OLD_ACHIEVE_DATA);
    }

    private void checkExpert(String expertId){
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        WalnutEventHandler nofityHandler = new WalnutEventHandler(this);

        WalnutExpertServiceHandler expertServiceHandler = new WalnutExpertServiceHandler(this);
        expertServiceHandler.checkExpert(restAdapter, expertId, nofityHandler, CHECK_EXPERT);

    }

    private static class WalnutEventHandler
            extends WalnutBaseNofityHandler<WalnutMainActivity, WalnutMainEvent> {

        private HeaderViewListAdapter headerAdapter;
        public WalnutEventHandler(WalnutMainActivity walnutMainActivity) {
            super(walnutMainActivity);
        }

        @Override
        public void doInitData(WalnutMainActivity o, List<WalnutMainEvent> data) {
            get().activityAdapter = new WalnutMainActivityAdapter(get());
            get().activityAdapter.setDataset(data);

            if(null != get().eventList){
                get().eventList.setAdapter(get().activityAdapter);
            }
            get().swipeRefreshLayout.setRefreshing(false);
            get().progress.setVisibility(View.GONE);

            if (data != null && data.size() > 9) {
                get().pageNumber ++;
            }
        }

        @Override
        public void doNewData(WalnutMainActivity o, List<WalnutMainEvent> data) {
            headerAdapter =
                    (HeaderViewListAdapter)get().eventList.getAdapter();
            WalnutMainActivityAdapter mAdapter = (WalnutMainActivityAdapter)headerAdapter.getWrappedAdapter();
            mAdapter.insertDataset(data);
            mAdapter.notifyDataSetChanged();

            get().swipeRefreshLayout.setRefreshing(false);
        }

        @Override
        public void doOldData(WalnutMainActivity o, List<WalnutMainEvent> data) {
            headerAdapter =
                    (HeaderViewListAdapter)get().eventList.getAdapter();
            WalnutMainActivityAdapter mAdapter = (WalnutMainActivityAdapter)headerAdapter.getWrappedAdapter();

            if (data != null) {
                if (data.size() > 9) {
                    get().pageNumber ++;
                }

                if (!data.isEmpty()) {
                    int count = mAdapter.getCount();

                    if (count % 10 != 0) {
                        int index = count - (count / 10) * 10;

                        if (index < data.size()) {
                            for (int i = index; i >= 0; i--) {
                                data.remove(i);
                            }

                            mAdapter.appendDataset(data);
                        }
                    } else {
                        mAdapter.appendDataset(data);
                    }
                }
            }

            mAdapter.notifyDataSetChanged();

            get().eventList.onLoadMoreComplete();
        }

        @Override
        public void handleOtherMessage(Message msg) {
            if(msg.what == USER_LOGIN){
                SeedsApp app = (SeedsApp)get().getApplication();
                HeroInfo loginUser = (HeroInfo)msg.getData().getSerializable(RetrofitNetworkService.RESULT_DATA);
                app.getSession().put(SeedsApp.LOGIN_USER, loginUser);
                PrefUtils.markUserPassword(get(), loginUser.userName, loginUser.password);
                PrefUtils.markUserId(get(), Integer.valueOf(loginUser.userId));

                get().checkExpert(loginUser.userId);

                ImageLoader imageLoader = new ImageLoader(get(), R.drawable.walnut_logo);
                imageLoader.loadImage(loginUser.headPortrait, get().logoView, true, false);
            }
            else if(msg.what == CHECK_EXPERT){
                ExpertInfo expertInfo = (ExpertInfo)msg.getData().getSerializable(RetrofitNetworkService.RESULT_DATA);

                SeedsApp app = (SeedsApp) get().getApplication();
                if(null != expertInfo){
                    app.getSession().put(SeedsApp.IS_EXPERT, "yes");
                }
                else {
                    app.getSession().put(SeedsApp.IS_EXPERT, "no");
                }
            }
        }
    }
}
